<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 17-11-6
 * Time: 下午2:40
 */

namespace common\models\credit_app;

use common\models\credit_old_app\SlOrder;
use yii\base\ErrorException;
use yii\db\Exception;
use yii\helpers\ArrayHelper;


/**
 * Class Order
 * @package common\models\credit_app
 *
 * @property OrderCert[] $certs
 * @property OrderCert $certVip
 * @property OrderCert $certSpouse
 * @property OrderCert[] $certGuarantors
 * @property array $certSigns
 * @property array $certVideoes
 * @property OrderCar $car
 * @property OrderOwner $owner
 * @property OrderAttachment $attachment
 * @property Branch $branch
 * @property OrderIndex[] $indexes
 * @property OrderIndex $hierarchyReview
 * @property OrderIndex $dataReview
 * @property Bank $bank
 * @property SlOrder $slOrder
 */
class Order extends \common\models\credit_app_tables\Order
{
    const STATUS_CREDIT_SUBMIT = 1;
    const STATUS_CREDIT_QUERY = 2;
    const STATUS_TRIAL_SUBMIT = 3;
    const STATUS_TRIAL_PASS = 4;
    const STATUS_INTERVIEW_SUBMIT = 5;
    const STATUS_INTERVIEW_BACK = 6;
    const STATUS_FINAL_JUDGMENT_SUBMIT = 7;
    const STATUS_INTERVIEW_PASS = 8;
    const STATUS_FINAL_JUDGMENT_PASS = 9;
    const STATUS_CANCEL = 10;
    const STATUS_BACK = 11;
    const STATUS_HAS_SETTLE = 12;
    const STATUS_HAS_DEAL = 13;
    const STATUS_AUDIT = 14;
    public static function getStatus()
    {
        $map = [
            self::STATUS_CREDIT_SUBMIT => '征信提交',
            self::STATUS_CREDIT_QUERY => '征信查询',
            self::STATUS_TRIAL_SUBMIT => '初审提交',
            self::STATUS_TRIAL_PASS => '初审通过',
            self::STATUS_INTERVIEW_SUBMIT => '面签提交',
            self::STATUS_INTERVIEW_BACK => '面签退单',
            self::STATUS_FINAL_JUDGMENT_SUBMIT => '终审提交',
            self::STATUS_INTERVIEW_PASS => '审核员审核通过',
            self::STATUS_FINAL_JUDGMENT_PASS => '终审通过',
            self::STATUS_CANCEL => '作废',
            self::STATUS_BACK => '退回',
            self::STATUS_HAS_SETTLE => '已结清',
            self::STATUS_HAS_DEAL => '已成交',
            self::STATUS_AUDIT => '审核中',
        ];
        return $map;
    }
    public static function getCanOptStatus()
    {
        $map = [
            self::STATUS_CREDIT_SUBMIT => '征信提交',
            self::STATUS_CREDIT_QUERY => '征信查询',
        ];
        return $map;
    }

    /**
     * 初审单提交
     * @throws ErrorException
     */
    public function trialSubmit()
    {
        $this->o_status = self::getStatus()[self::STATUS_TRIAL_SUBMIT];
        $this->o_first_time = time();
        $this->o_audit_priority = "";
        $this->o_bank_time = $this->o_bank_time?$this->o_bank_time:time();
        if ($this->owner){
            $this->owner->ot_status = 'ok';
            $this->owner->ot_dateline = time();
        }else{
            throw new ErrorException("没有找到购车人信息");
        }
        if ($this->car){
            $this->car->ot_status = 'ok';
            $this->car->ot_dateline = time();
            $this->o_loan_money = $this->car->ot_loan_limit;
        }else{
            throw new ErrorException("没有找到车辆信息");
        }
        if ($this->attachment){
            $this->attachment->oa_status = 'ok';
            $this->attachment->oa_dateline = time();
        }else{
            throw new ErrorException("没有找到附件信息");
        }
        if($this->car->ot_loan_limit>300000 || (!empty($this->branch->br_audit_urealname) && $this->car->ot_loan_limit<=80000)){
            $this->o_audit_priority = 3;
            $this->o_final_perch = $this->car->ot_loan_limit>300000?109:$this->branch->br_audit_uid;//109为大额审核员ID
        }elseif(!empty($this->branch->br_audit_urealname) && $this->car->ot_loan_limit<=300000 && $this->car->ot_loan_limit>80000){
            $this->o_audit_priority =1;
            $this->o_final_perch = $this->branch->br_audit_uid;
        }elseif(empty($this->branch->br_audit_urealname)){
            if($this->car->ot_loan_limit<=80000){
                $this->o_audit_priority = 2;
            }elseif($this->car->ot_loan_limit<=300000 && $this->car->ot_loan_limit>80000){
                $this->o_audit_priority = 0;
            }
            $this->o_final_perch = 0;
        }
        if ($this->hierarchyReview){
//            throw new ErrorException("已经有层级审核");
            $this->hierarchyReview->delete();
        }
        $h_review = new OrderIndex();
        $h_review->ot_id = $this->o_id;
        $h_review->ot_type = $h_review::TYPE_HIERARCHY_REVIEW;
        $h_review->ot_dateline = time();
        if ($this->dataReview){
//            throw new ErrorException("已经有资料审核");
            $this->dataReview->delete();
        }
        $d_review = new OrderIndex();
        $d_review->ot_id = $this->o_id;
        $d_review->ot_type = $d_review::TYPE_DATA_REVIEW;
        $d_review->ot_dateline = time();
        $trans = \Yii::$app->db_app->beginTransaction();
        try{
            $this->save(false);
            $this->owner->save(false);
            $this->car->save(false);
            $this->attachment->save(false);
            $h_review->save(false);
            $d_review->save(false);
            $trans->commit();
            return [
                'order' => $this->toArray(),
                'owner' => $this->owner->toArray(),
                'car' => $this->car->toArray(),
                'attachment' => $this->attachment->toArray(),
            ];
        }catch (Exception $e){
            $trans->rollBack();
            throw $e;
        }
    }

    /**
     * @param $id
     * @return null|static
     */
    public static function findActiveOneById($id)
    {
        return static::findOne(['o_id' => $id]);
    }

    /**
     * 所有的征信
     * @return \yii\db\ActiveQuery
     */
    public function getCerts()
    {
        return $this->hasMany(OrderCert::className(), ['ct_oid' => 'o_id']);
    }

    /**
     * 本人的征信
     * @return \yii\db\ActiveQuery
     */
    public function getCertVip()
    {
        return $this->hasOne(OrderCert::className(), ['ct_oid' => 'o_id'])->where(['ct_key' => OrderCert::KEY_VIP]);
    }

    /**
     * 配偶的征信
     * @return \yii\db\ActiveQuery
     */
    public function getCertSpouse()
    {
        return $this->hasOne(OrderCert::className(), ['ct_oid' => 'o_id'])->where(['ct_key' => OrderCert::KEY_SPOUSE]);
    }

    /**
     * 担保人的征信
     * @return \yii\db\ActiveQuery
     */
    public function getCertGuarantors()
    {
        return $this->hasMany(OrderCert::className(), ['ct_oid' => 'o_id'])->where(['ct_key' => OrderCert::KEY_GUARANTOR]);
    }

    /**
     * @return array
     */
    public function getCertSigns()
    {
        $x = [];
        foreach ($this->certs as $k => $v) {
            if ($v->ct_sign)
                $x = ArrayHelper::merge($x, unserialize($v->ct_sign));
        }
        return $x;
    }

    /**
     * @return array
     */
    public function getCertVideoes()
    {
        $x = [];
        foreach ($this->certs as $k => $v) {
            if ($v->ct_video)
                $x = ArrayHelper::merge($x, unserialize($v->ct_video));
        }
        return $x;
    }

    /**
     * 车辆
     * @return \yii\db\ActiveQuery
     */
    public function getCar()
    {
        return $this->hasOne(OrderCar::className(), ['ot_oid' => 'o_id']);
    }

    /**
     * 购车人信息
     * @return \yii\db\ActiveQuery
     */
    public function getOwner()
    {
        return $this->hasOne(OrderOwner::className(), ['ot_oid' => 'o_id']);
    }

    /**
     * 附件信息
     * @return \yii\db\ActiveQuery
     */
    public function getAttachment()
    {
        return $this->hasOne(OrderAttachment::className(), ['oa_oid' => 'o_id']);
    }

    /**
     * 银行信息
     * @return \yii\db\ActiveQuery
     */
    public function getBranch()
    {
        return $this->hasOne(Branch::className(), ['br_id' => 'o_branch_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getIndexes()
    {
        return $this->hasMany(OrderIndex::className(), ['ot_id' => 'o_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getHierarchyReview()
    {
        return $this->hasOne(OrderIndex::className(), ['ot_id' => 'o_id'])->where(['ot_type' => OrderIndex::TYPE_HIERARCHY_REVIEW]);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getDataReview()
    {
        return $this->hasOne(OrderIndex::className(), ['ot_id' => 'o_id'])->where(['ot_type' => OrderIndex::TYPE_DATA_REVIEW]);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getBank()
    {
        return $this->hasOne(Bank::className(), ['bk_id' => 'o_bank_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getSlOrder()
    {
        return $this->hasOne(SlOrder::class, ['o_fcustid' => 'o_id']);
    }
}